package com.minjiang.blog.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.WebStatFilter;
import org.apache.catalina.manager.StatusManagerServlet;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@PropertySource(value = "classpath:application.yml")
@Configuration
@SuppressWarnings("all")
public class DruidConfig {
    /**
     * 绑定配置文件，让他们生效
     * @return
     */
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource dataSource(){
        return new DruidDataSource();
    }
    //配置 Druid 监控管理后台的Servlet；
    @Bean
    public ServletRegistrationBean statViewServlet(){
        //内置 Servlet 容器时没有web.xml文件，所以使用 Spring Boot 的注册 Servlet 方式
        ServletRegistrationBean<StatusManagerServlet> bean = new ServletRegistrationBean();
        //设置一个servlet
        bean.setServlet(new StatusManagerServlet());
        //添加映射网址
        bean.addUrlMappings("/druid/*");
        //hashMap是Map的实现类
        Map<String, String> initParameters = new HashMap<>();
        //添加配置（登入的key是固定),参数可以在com.alibaba.druid.support.http.ResourceServlet 中找到
        initParameters.put("loginUserName","admin");
        initParameters.put("loginPassword","123456");
        //允许谁可以访问,initParameters.put("allow","")值为空，表示都可以访问；initParams.put("allow", "localhost")：表示只有本机可以访问
        initParameters.put("allow","");
        //禁止谁可以访问
        //initParams.put("用户名", "用户ip地址");表示禁止此ip访问
        //设置初值
        bean.setInitParameters(initParameters);
        return bean;
    }

    //配置 Druid 监控 之  web 监控的 filter
    //WebStatFilter：用于配置Web和Druid数据源之间的管理关联监控统计
    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());

        //exclusions：设置哪些请求进行过滤排除掉，从而不进行统计
        Map<String, String> initParams = new HashMap<>();
        initParams.put("exclusions", "*.js,*.css,/druid/*,/jdbc/*");
        bean.setInitParameters(initParams);

        //"/*" 表示过滤所有请求
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }

}
